<template>
  <div id="HospitalAdmissionRanking">
    <div class="bg-color-black">
      <div class="title-bar">
        <div class="d-flex">
          <span>
            <icon name="align-left" class="text-icon"></icon>
          </span>
          <div class="d-flex">
            <span class="text mx-2">送往医院排名</span>
          </div>
        </div>
        <span class="text total-count">总数：<span style="color: #3de7c9;">{{ total }}</span></span>
      </div>
      <div class="d-flex ai-center flex-column body-box">
        <dv-scroll-board class="dv-scr-board" :config="config" />
      </div>
    </div>
  </div>
</template>

<script>
import bus from "@/bus";
import {getUnitCalItemsWithNoAuthorization} from "@/api/UnitCalculate";
import config from "@/config";
import { getLast24HoursRange } from "@/utils/dateUtil";

export default {
  data() {
    return {
      standardData: {
        beginDateTime: '',
        endDateTime: '',
        columnsData: [
          {
            columnHeadType: 1,
            commGroupInfo: {
              isCommonGroup: true,
              category: "AOISWDD",
              categoryGroup: "AOISWDD_1"
            },
            dataIndex: "CATE"
          },
          {
            columnHeadType: 1,
            calculateIden: {
              title: "出车数"
            },
            calculateInfo: {
              offset: 0,
              dataCategory: 0,
              valueCategory: 0,
              count: true,
              differenceCount: false,
              proportion: false
            },
            dataIndex: "CCS"
          }
        ],
        verticalGroups: [
          {
            category: "AOISWDD",
            categoryGroup: "AOISWDD_1",
            level: 1,
            title: "送往医院"
          }
        ],
        screens: [
          {
            ref: "EPAIAREA_CODE",
            checkIden: "EPAIAREA_CODE_1",
            rlevantData: {
              iden: "EPAIAREA_CODE_1",
              filterType: 2,
              value: [
                {
                  value: config.xzbm,
                  xzbm: config.xzbm
                }
              ]
            }
          }
        ],
        orderUnits: [
          {
            dataIndex: "CCS",
            orderDirection: "descend"
          }
        ]
      },
      total: 0,
      config: {
        header: ['医院', '数量'],
        data: [],
        rowNum: 6, //表格行数
        headerHeight: 35,
        headerBGC: '#0f1325', //表头
        oddRowBGC: '#0f1325', //奇数行
        evenRowBGC: '#171c33', //偶数行
        index: true,
        columnWidth: [50, 160],
        align: ['center', 'center', 'center']
      }
    }
  },
  async created() {
    this.fetchData()
    // 监听全局刷新事件
    this.refreshHandler = () => {
      console.log("定时刷新：preAcceptSourceChart")
      this.fetchData();
    }
    bus.$on('refresh-all-data', this.refreshHandler)
  },
  methods: {
    async fetchData() {
      const { beginDateTime, endDateTime } = getLast24HoursRange();
      this.standardData.beginDateTime = beginDateTime;
      this.standardData.endDateTime = endDateTime;
      const res = await getUnitCalItemsWithNoAuthorization(this.standardData);
      if (res.code === 200 && res.isSuccess) {
        try {
          const entityList = JSON.parse(res.entity);
          if (entityList && entityList.length > 0) {
            console.log("HospitalAdmissionRanking entityList: ", entityList);
            this.processData(entityList);
          } else {
            this.resetData();
          }
        } catch (e) {
          console.error('entity 解析失败', e);
        }
      }
    },
    // 重置数据
    resetData() {
      this.total = 0;
      this.config = {
        ...this.config,
        data: []
      };
    },
    // 处理接口返回数据
    processData(entityList) {
      if (!entityList || !entityList.length) {
        this.resetData();
        return;
      }

      // 分离合计项和普通项
      const totalItem = entityList.find(item => item.CATE === '合计');
      const normalItems = entityList.filter(item => item.CATE !== '合计' && item.CATE); // 排除空类型

      // 设置总数（优先使用合计项，没有则计算总和）
      this.total = totalItem
          ? Number(totalItem.CCS)
          : normalItems.reduce((sum, item) => sum + Number(item.CCS), 0);

      // 组装图表数据
      this.config = {
        ...this.config,
        data: normalItems.map(item => [item.CATE, `<span class='colorGrass'>${Number(item.CCS) || 0}</span>`])
      };

    }
  },
  beforeDestroy() {
    bus.$off('refresh-all-data', this.refreshHandler)
  }
};
</script>

<style lang="scss" scoped>
$box-height: 100%;
$box-width: 300px;
#HospitalAdmissionRanking {
  $box-height: 100%;
  $box-width: 100%;
  padding: 5px 5px 5px;
  height: $box-height;
  width: $box-width;
  border-radius: 5px;

  .bg-color-black {
    padding: 0;
    height: $box-height;
    width: $box-width;
    border-radius: 10px;
  }

  .title-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0px 5px 20px;
  }

  .text {
    color: #c3cbde;
  }

  .total-count {
    font-size: 14px;
    white-space: nowrap;
  }

  .body-box {
    border-radius: 10px;
    overflow: auto;
    height: 100%;
    .dv-cap-chart {
      width: 100%;
      height: 250px;
    }
  }
}
</style>
